package com.qiushibaike;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class Home extends Activity {
	private WebView view;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.main);
		this.view = (WebView) this.findViewById(R.id.webview);
		this.view.getSettings().setJavaScriptEnabled(true);
		this.view.getSettings().setBuiltInZoomControls(true);
		this.view.setWebViewClient(new QiuShiBaiKeClient());
		this.view.loadUrl("http://www.qiushibaike.com");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && this.view.canGoBack())
		{
			this.view.goBack();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		ProgressDialog dialog = new ProgressDialog(this);
		dialog.setMessage(this.getResources().getString(R.string.loading));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		return dialog;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}


	private class QiuShiBaiKeClient extends WebViewClient {
		private boolean isFirstTime = true;

		@Override
		public void onReceivedError(final WebView view, int errorCode,
				String description, String failingUrl) {
			if (errorCode == -2) {
				AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
				builder.setIcon(R.drawable.icon);
				builder.setTitle(R.string.page_error_title);
				builder.setMessage(R.string.page_error);
				builder.setNegativeButton(R.string.page_reload, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						view.reload();
					}
				});
				builder.show();
			} else {
				super.onReceivedError(view, errorCode, description, failingUrl);
			}
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if (this.isFirstTime) {
				dismissDialog(0);
				this.isFirstTime = false;
			}

			super.onPageFinished(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (this.isFirstTime) {
				showDialog(0);
			}

			view.setVisibility(View.VISIBLE);
			super.onPageStarted(view, url, favicon);
		}
	}
}